package cn.aixuegao.common.exception;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.aixuegao.common.exception.enums.IceyExceptionEnum;

/**
 * 提供统一的异常处理，只需要在抛出异常的时候 throw new Exception("some message") 或者  throw new XtqException("some message")即可
 * @author hxy
 * @version 0.0.1
 *
 */
@ControllerAdvice
public class GlobalExceptionHandler {
	
	@ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
		e.printStackTrace();
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName("error");
        return mav;
    }
	
	@ExceptionHandler(value = IceyException.class)
    @ResponseBody
    public ErrorInfo<String> jsonErrorHandler(HttpServletRequest req, IceyException e) throws Exception {
		e.printStackTrace();
		ErrorInfo<String> errorInfo = new ErrorInfo<>(IceyExceptionEnum.FAILED);
        errorInfo.setData("Some Data");
        errorInfo.setUrl(req.getRequestURL().toString());
        return errorInfo;
    }
}
